<template>
  <div :class="{ hidden }">
    <div class="banner">
      <div class="container">
        <h1>
          <div>
            在线文档查看
            <input class="file-select" type="file" @change="handleChange" />
          </div>
        </h1>
      </div>
    </div>

    <div class="container">
      <div v-show="loading" class="well loading">正在加载中，请耐心等待...</div>
      <div v-show="!loading" class="well" ref="output"></div>
    </div>


  </div>
</template>
  
<script>
import { getExtend, readBuffer, render } from "@/components/util";

import { parse } from "qs";

/**
 * 支持嵌入式显示，基于postMessage支持跨域
 * 示例代码：
 *
 */
export default {
  name: "HelloWorld",
  props: {
    file: Blob || Function,
  },
  data() {
    return {
      // 加载状态跟踪
      loading: false,
      // 上个渲染实例
      last: null,
      // 隐藏头部，当基于消息机制渲染，将隐藏
      hidden: false,
      // data: {
      //   url: 'http://192.168.0.129:8081/wzbxt/pic/wzbxt_zccx_file/20230403/%E8%BF%90%E8%B4%B9%E8%AE%A1%E7%AE%97%E6%9D%83%E9%99%90%E9%85%8D%E7%BD%AE%E8%A1%A8.xlsx',
      //   name: '项目.xlsx'
      // }
      // data: {
      //   url: 'http://192.168.0.129:8081/wzbxt/pic/wzbxt_zccx_file/20230403/%E8%BF%90%E8%B4%B9%E8%AE%A1%E7%AE%97%E5%9F%B9%E8%AE%ADppt.pptx',
      //   name: '项目.pptx'
      // }
      // data: {
      //   url: ' http://192.168.0.129:8081/wzbxt/pic/wzbxt_zccx_file/23977aeb405d4cf4b276d899696ed46c/001.pdf',
      //   name: '项目.pdf'
      // }
      // data: {
      //   url: 'http://192.168.0.129:8081/wzbxt/pic/wzbxt_zccx_file/20230403/456.docx',
      //   name: '项目.docx'
      // }


      data: {
        url: 'http://192.168.0.129:8081/wzbxt/pic/wzbxt_zccx_file/20230403/159.xls',
        name: '项目.xls'

      }




    };
  },
  created() {
    // 允许使用预留的消息机制发送二进制数据，必须在url后添加?name=xxx.xxx&from=xxx
    const { from, name } = parse(location.search.substr(1));
    if (from) {
      window.addEventListener("message", (event) => {
        const { origin, data: blob } = event;
        if (origin === from && blob instanceof Blob) {
          // 构造响应，自动渲染
          const file = new File([blob], name, {});
          this.hidden = true;
          this.handleChange({ target: { files: [file] } });
        }
      });
    }

  },
  mounted() {
    this.getFile(this.data.url, this.data.name)
  },
  watch: {
    file: {
      //  拿到file文件  utils文件中blobToFile.js拿到接口返回的流文件转成file文件
      handler(newValue, oldValue) {
        if (newValue.type) {
          this.handleChange(newValue)
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    async handleChange(e) {
      this.loading = true;
      try {
        debugger
        // const [file] = e.target.files;
        const file = e;
        const arrayBuffer = await readBuffer(file);
        this.loading = false;
        this.last = await this.displayResult(arrayBuffer, file);
        // debugger
      } catch (i) {
        console.log('i: ', i);

      } finally {
        this.loading = false;
      }
    },
    displayResult(buffer, file) {
      // 取得文件名
      const { name } = file;
      // 取得扩展名
      const extend = getExtend(name);
      // 输出目的地
      const { output } = this.$refs;
      // 生成新的dom
      const node = document.createElement("div");
      // 添加孩子，防止vue实例替换dom元素
      debugger
      if (this.last) {
        output.removeChild(this.last.$el);
        this.last.$destroy();
      }
      debugger
      const child = output.appendChild(node);
      // 调用渲染方法进行渲染
      return new Promise((resolve, reject) => {
        render(buffer, extend, child).then(resolve).catch(reject)
      }
      );
    },
    async getFile(url, fileName) {
      // 通过 url 获取到 File
      function getFileFromUrl(url, fileName) {
        return new Promise((resolve, reject) => {
          let blob = null
          let xhr = new XMLHttpRequest()
          xhr.open('GET', url)
          // 这里设置接收的响应体类型(试了不设置也正常)
          // xhr.setRequestHeader('Accept', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
          xhr.responseType = 'blob'
          // 加载时处理(异步)
          xhr.onload = () => {
            // 获取返回结果
            blob = xhr.response
            console.log('blob:', blob)
            let file = new File([blob], fileName, { type: blob.type })
            // 返回结果
            resolve(file)
          }
          xhr.onerror = (e) => {
            reject(e)
          }
          // 发送
          xhr.send()
        })
      }

      // var arr = url.split(','), mime = arr[0].match(/:(.*?);/)[1],
      //   bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
      // while (n--) {
      //   u8arr[n] = bstr.charCodeAt(n);
      // }
      // return new File([u8arr], fileName, { type: mime });
      // }
      debugger
      const file = await getFileFromUrl(url, fileName)
      console.log('file:', file)
      this.handleChange(file)
    }
    // 这个地址没有跨域问题 https://img2.baidu.com/it/u=2149607209,2234358780&fm=253&fmt=auto&app=138&f=JPEG?w=450&h=255  
    // let url1 = 'https://bargaining.oss-cn-shenzhen.aliyuncs.com/upload/2020/9/15/1600153305138.xlsx?Expires=4753753305&OSSAccessKeyId=LTAIHonqvbarNqaq&Signature=f%2Fstpo0rlI2TUkbGiNZzo6fT%2Fto%3D'
    // const fileName = '文件名称'
    // getFile(url1, fileName)

  },
};
</script>
  
  <!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.banner {
  overflow: auto;
  text-align: center;
  /* background-color: #12b6ff; */
  color: #000;
  position: relative;
}

.hidden .banner {
  display: none;
}

.hidden .well {
  height: calc(100vh - 12px);
}

.file-select {
  position: absolute;
  left: 5%;
  top: 17px;
  margin-left: 20px;
}

.banner div {
  color: #000;
}

.banner h1 {
  font-size: 20px;
  line-height: 2;
  margin: 0.5em 0;
}

.well {
  display: block;
  background-color: #f2f2f2;
  border: 1px solid #ccc;
  margin: 5px;
  width: calc(100% - 12px);
  height: calc(100vh - 73px);
  overflow: auto;
}

.loading {
  text-align: center;
  padding-top: 50px;
}

.messages .warning {
  color: #cc6600;
}
</style>
  
<style>
.pptx-wrapper {
  max-width: 1000px;
  margin: 0 auto;
}
</style>
  